﻿using LogisticsTrackingWebApi_V3.Models;
using LogisticsTrackingWebApi_V3.Services;
using Microsoft.Extensions.Caching.Memory;

namespace LogisticsTrackingWebApi_V3.ServicesImpl.Decorators
{

    /// <summary>
    /// 缓存装饰器 - 为物流查询添加缓存功能
    /// </summary>
    public class CachingDecorator : ILogisticsProvider
    {
        private readonly ILogisticsProvider _provider;
        private readonly IMemoryCache _cache;
        private readonly MemoryCacheEntryOptions _cacheOptions;

        public CachingDecorator(ILogisticsProvider provider, IMemoryCache cache)
        {
            _provider = provider;
            _cache = cache;

            // 缓存配置：10分钟过期
            _cacheOptions = new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromMinutes(10))
                .SetSlidingExpiration(TimeSpan.FromMinutes(5));
        }

        public string CompanyCode => _provider.CompanyCode;
        public string CompanyName => _provider.CompanyName;

        public async Task<LogisticsInfo> QueryTrackingAsync(string trackingNumber)
        {
            var cacheKey = $"logistics:{_provider.CompanyCode}:{trackingNumber}";

            // 尝试从缓存获取
            if (_cache.TryGetValue(cacheKey, out LogisticsInfo? cachedResult))
            {
                return cachedResult;
            }

            // 缓存未命中，调用实际查询
            var result = await _provider.QueryTrackingAsync(trackingNumber);

            // 存入缓存
            _cache.Set(cacheKey, result, _cacheOptions);

            return result;
        }

        public bool MatchTrackingNumber(string trackingNumber)
        {
            return _provider.MatchTrackingNumber(trackingNumber);
        }
    }

}
